//不使用JQuery版的

import html2canvas from 'html2canvas';
import JsPDF from 'jspdf';


function downloadPDF(ele, pdfName) {
    window.scroll(0, 0);
    const targetDom = document.querySelector("#copy"); // 获取要截图的元素
    const box = document.querySelector("#pdfDom")
    const copyDom =targetDom; // 克隆一个
    copyDom.style.width = targetDom.scrollWidth + "px";
    copyDom.style.height = targetDom.scrollHeight + "px";
    document.body.appendChild(copyDom); // 添加
    setTimeout(() => {
        html2canvas(copyDom, {
            width: targetDom.scrollWidth,
            height: targetDom.scrollHeight,
            scrollY:0,
            scrollY:0,
            useCORS: true,
        }).then((canvas) => {
            document.body.removeChild(copyDom); // 用完要删除
            // return false
            var contentWidth = canvas.width;
            var contentHeight = canvas.height;
            //一页pdf显示html页面生成的canvas高度;
            var pageHeight = contentWidth / 592.28 * 841.89;
            //未生成pdf的html页面高度
            var leftHeight = contentHeight;
            //页面偏移
            var position = 0;
            //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
            var imgWidth = 595.28;
            var imgHeight = 595.28 / contentWidth * contentHeight;

            var pageData = canvas.toDataURL('image/jpeg', 1.0);
            var pdf = new JsPDF('', 'pt', 'a4');
            //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
            //当内容未超过pdf一页显示的范围，无需分页
            if (leftHeight < pageHeight) {
                //在pdf.addImage(pageData, 'JPEG', 左，上，宽度，高度)设置在pdf中显示；
                pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
                // pdf.addImage(pageData, 'JPEG', 20, 40, imgWidth, imgHeight);
            } else {    // 分页
                while (leftHeight > 0) {
                    pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
                    leftHeight -= pageHeight;
                    position -= 841.89;
                    //避免添加空白页
                    if (leftHeight > 0) {
                        pdf.addPage();
                    }
                }
            }

            pdf.save(pdfName);
            box.appendChild(copyDom);
        });
    }, 200);
}


export default {
    downloadPDF,
}
/**
 * 1633 4043 80 30 1903 1920 3266 8086
   1633 4043 2321.2101877490377 4043
   1633 4043 80 30 1903 1920 3266 8086
   1633 4043 2321.2101877490377 4043
   1633 4043 80 30 1903 1920 3266 8086
   1633 4043 2321.2101877490377 4043
   1633 4043 80 30 1903 1920 3266 8086
   1633 4043 2321.2101877490377 4043
   1633 4043 80 30 1903 1920 3266 8086


   1633 4043 80 30 1903 1920 3266 8086
   1633 4043 2321.2101877490377 4043

 */